#!/bin/bash

# 设置颜色输出
print_green() {
    echo -e "\033[32m$1\033[0m"
}

print_red() {
    echo -e "\033[31m$1\033[0m"
}

print_yellow() {
    echo -e "\033[33m$1\033[0m"
}

# 设置变量
FRONTEND_DIR="pdf-toolkit-frontend"
BUILD_DIR="$FRONTEND_DIR/build"
DEPLOY_DIR="/var/www/pdf-toolkit"
NGINX_CONF="/etc/nginx/sites-available/pdf-toolkit-frontend"

# 检查 Node.js 环境
check_nodejs() {
    print_yellow "检查 Node.js 环境..."
    if ! command -v node &> /dev/null; then
        print_red "错误: Node.js 未安装"
        print_yellow "请安装 Node.js: https://nodejs.org/"
        exit 1
    fi
    node_version=$(node -v)
    print_green "Node.js 版本: $node_version"
}

# 安装依赖
install_dependencies() {
    print_yellow "安装项目依赖..."
    cd $FRONTEND_DIR || exit 1
    if [ ! -f "package.json" ]; then
        print_red "错误: 未找到 package.json"
        exit 1
    fi
    npm install
    if [ $? -ne 0 ]; then
        print_red "依赖安装失败"
        exit 1
    fi
    print_green "依赖安装完成"
}

# 构建项目
build_project() {
    print_yellow "开始构建项目..."
    npm run build
    if [ $? -ne 0 ]; then
        print_red "构建失败"
        exit 1
    fi
    print_green "构建完成"
}

# 创建 Nginx 配置
create_nginx_config() {
    cat > "$NGINX_CONF" << 'EOF'
server {
    listen 8001;
    server_name localhost;

    root /var/www/pdf-toolkit;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
        add_header Cache-Control "no-cache, no-store, must-revalidate";
    }

    location /static {
        expires 1y;
        add_header Cache-Control "public";
    }

    location /api {
        proxy_pass http://localhost:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}
EOF
}

# 配置 Nginx
setup_nginx() {
    print_yellow "配置 Nginx..."
    create_nginx_config
    sudo ln -sf "$NGINX_CONF" /etc/nginx/sites-enabled/
    sudo nginx -t
    if [ $? -ne 0 ]; then
        print_red "Nginx 配置测试失败"
        exit 1
    fi
    sudo systemctl restart nginx
    print_green "Nginx 配置完成"
}

# 部署文件
deploy_files() {
    print_yellow "部署文件..."
    sudo mkdir -p "$DEPLOY_DIR"
    sudo cp -r "$BUILD_DIR"/* "$DEPLOY_DIR"/
    sudo chown -R www-data:www-data "$DEPLOY_DIR"
    sudo chmod -R 755 "$DEPLOY_DIR"
    print_green "文件部署完成"
}

# 主函数
main() {
    print_green "=== PDF工具箱前端部署脚本 ==="
    check_nodejs
    install_dependencies
    build_project
    setup_nginx
    deploy_files
    print_green "=== 部署完成 ==="
    print_green "前端应用已部署到: http://localhost:8001"
}

# 执行主函数
main 